//
//  CNKIMainView.m
//  CNKICommunity
//
//  Created by wei on 17/3/9.
//  Copyright © 2017年 CNKI. All rights reserved.
//

#import "CNKIMainView.h"


static const CGFloat TopscollviewHeight = 40.0f;//顶部视图的高度
static const CGFloat buttonMargin = 10.0f;//按钮之间的间隔
static const CGFloat buttonNormalFont = 17.0f;//按钮文字的正常大小
static const CGFloat buttonSelectFont = 18.0f;//按钮文字的正常大小

@interface CNKIMainView()<UIScrollViewDelegate>
{
    UIScrollView *_mainScrollview;//界面滑动的ScrollView
    NSMutableArray *_topButtons;//顶部view的按钮数组
    NSMutableArray *_childviews;//存放controller的view数组
    UIView *_lineview;//底部分割线
    UIImageView *_shadowImageview;//按钮背后下划线图片
    
}


@end

@implementation CNKIMainView

#pragma mark--初始化方法
-(instancetype)init
{
    self = [super init];
    if (self) {
        [self buildUI];
    }
    return self;
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self buildUI];
    }
    return self;
}
-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self buildUI];
    }
    return self;
}
-(void)buildUI
{
    //初始化的数组
    _topButtons = [NSMutableArray array];
    _childviews = [NSMutableArray array];
    
    _selectIndex = 0;
    
    //创建顶部scrollview
    _topScollview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, TopscollviewHeight)];
    _topScollview.showsHorizontalScrollIndicator = NO;
    _topScollview.backgroundColor = [UIColor colorWithRed:247.0f/255.0f green:246.0f/255.0f blue:245.0f/255.0f alpha:1];
    [self addSubview:_topScollview];
    
    //创建展示视图控制器的scrollview
    _mainScrollview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, TopscollviewHeight, SCREENWIDTH, SCREENHEIGHT - TopscollviewHeight)];
    _mainScrollview.delegate = self;
    _mainScrollview.pagingEnabled = YES;
    _mainScrollview.userInteractionEnabled = YES;
    _mainScrollview.showsVerticalScrollIndicator = NO;
    [self addSubview:_mainScrollview];
    
    //分割线
    _lineview = [UIView new];
    _lineview.frame = CGRectMake(0, TopscollviewHeight, SCREENWIDTH, 0.5);
    _lineview.backgroundColor =[UIColor colorWithRed:204.0f/255.0f green:204.0f/255.0f blue:204.0f/255.0f alpha:1];
    [self addSubview:_lineview];
    
    //创建阴影view
    _shadowImageview = [[UIImageView alloc]init];
    _shadowImageview.backgroundColor = _btnSelectColor;
    [_topScollview addSubview:_shadowImageview];
    
}

//更新view 加入button  和 views
-(void)layoutSubviews
{
    [super layoutSubviews];
    
    [self updateButtons];
    
    [self updateShadows];
    
    [self updateMainScorllview];
    
}
-(void)updateShadows
{
    UIButton *btn = _topButtons[_selectIndex];
    _shadowImageview.frame = CGRectMake(btn.x, CGRectGetMaxY(btn.frame) - 1.5, btn.width, 1.5);
    _shadowImageview.backgroundColor = _btnSelectColor;
}
-(void)updateButtons
{
    CGFloat BtnXOffset = buttonMargin;
    for (int i = 0; i < _topButtons.count; i++)
    {
        UIButton *btn = _topButtons[i];
        CGSize RecSize = [self buttonSizeOfTitle:btn.currentTitle];
        btn.frame = CGRectMake(BtnXOffset, 0, RecSize.width, TopscollviewHeight);
        [btn setTitleColor:_btnNormalColor forState:UIControlStateNormal];
        [btn setTitleColor:_btnSelectColor forState:UIControlStateSelected];
        BtnXOffset += (RecSize.width + buttonMargin);
        if (i == _selectIndex)
        {
            btn.titleLabel.font = [UIFont systemFontOfSize:buttonSelectFont];
            btn.selected = YES;
        }
        else
        {
            btn.titleLabel.font = [UIFont systemFontOfSize:buttonNormalFont];
            btn.selected = NO;
        }
        
    }
    
    //设置顶部视图的consize
    UIButton *btn = _topButtons.lastObject;
    _topScollview.contentSize = CGSizeMake(CGRectGetMaxX(btn.frame) + buttonMargin , 0);
    
}
-(void)updateMainScorllview
{
    _mainScrollview.contentSize = CGSizeMake(_viewControllers.count * SCREENWIDTH, 0);
}
#pragma mark--setter方法
-(void)setViewControllers:(NSMutableArray *)viewControllers
{
    _viewControllers = viewControllers;
    
    //用于显示第一页面
    [_viewControllers[_selectIndex] view].frame = CGRectMake(_selectIndex * SCREENWIDTH, 0, SCREENWIDTH, SCREENHEIGHT);
    [_mainScrollview addSubview:[_viewControllers[_selectIndex] view]];
  
    
    //添加button
    for (int i = 0; i < viewControllers.count; i++)
    {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:[viewControllers[i] title] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:buttonNormalFont];
        [btn addTarget:self action:@selector(buttonSelectedMethod:) forControlEvents:UIControlEventTouchUpInside];
        
        [_topScollview addSubview:btn];
        [_topButtons addObject:btn];
    }
}
-(void)setSelectIndex:(NSInteger)selectIndex
{
   
}
-(void)buttonSelectedMethod:(UIButton*)sender
{
    [self updateUIWithSelectedIndex:[_topButtons indexOfObject:sender] ByButton:YES];
}

#pragma mark 核心偏移方法
//用户自己滑的不用更新mainScrollview 点击按钮的需要更新
-(void)updateUIWithSelectedIndex:(NSInteger)index ByButton:(BOOL)bybutton
{
    _selectIndex = index;
    for (UIButton *btn in _topButtons)
    {
        if ([_topButtons indexOfObject:btn] == _selectIndex)
        {
            btn.selected = YES;
            btn.titleLabel.font = [UIFont systemFontOfSize:buttonSelectFont];
        }else
        {
            btn.selected = NO;
            btn.titleLabel.font = [UIFont systemFontOfSize:buttonNormalFont];
        }
    }
    
    //为了进入此页面全部显示，将加在子view放在此，只有点击和滑动才会显示
    [_viewControllers[index] view].frame = CGRectMake(index * SCREENWIDTH, 0, SCREENWIDTH, SCREENHEIGHT);
    [_mainScrollview addSubview:[_viewControllers[index] view]];
    
    
    [UIView animateWithDuration:0.35 animations:^{
       //更新topView的contentoffset
        [self adjustTopsorllview:_selectIndex];
        //更新shadow的frame
        [self updateShadows];
    } completion:^(BOOL finished) {
        //点的是按钮
        if (bybutton)
        {
            [_mainScrollview setContentOffset:CGPointMake(_selectIndex * SCREENWIDTH, 0)];
        }
    }];
}
-(void)adjustTopsorllview:(NSInteger)index
{
    CGFloat topOffset = 0;
    UIButton *btn = _topButtons[index];
    //目的让被点击的按钮显示在屏幕中央
    topOffset = CGRectGetMidX(btn.frame) - SCREENWIDTH / 2;
    if (topOffset <= 0)
    {
        topOffset = 0;
    }
    if (topOffset >= _topScollview.contentSize.width - SCREENWIDTH)
    {
        //最后两个按钮不能屏幕中间显示了，直接显示到scrollview的最后即可，不然会有空白出来
        topOffset = _topScollview.contentSize.width - SCREENWIDTH;
    }
    [_topScollview setContentOffset:CGPointMake(topOffset, 0)];
    
}

#pragma mark--Scrollviewdelegate
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger index = scrollView.contentOffset.x / SCREENWIDTH;
    [self updateUIWithSelectedIndex:index ByButton:NO];
}


#pragma mark--附加方法

//按钮宽度
-(CGSize)buttonSizeOfTitle:(NSString*)title
{
    NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin |
    NSStringDrawingUsesFontLeading;
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setLineBreakMode:NSLineBreakByTruncatingTail];
    NSDictionary *attributes = @{ NSFontAttributeName : [UIFont boldSystemFontOfSize:buttonSelectFont], NSParagraphStyleAttributeName : style };
    CGSize textSize = [title boundingRectWithSize:CGSizeMake(SCREENWIDTH, TopscollviewHeight)
                                          options:opts
                                       attributes:attributes
                                          context:nil].size;
    return textSize;
}



@end
